package com.marketingcenter.service.impl;

import com.marketingcenter.entity.CountCard;
import com.marketingcenter.repository.CountCardRepository;
import com.marketingcenter.service.CountCardService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 次数权益卡服务实现类
 */
@Service
public class CountCardServiceImpl extends PromotionServiceImpl<CountCard> implements CountCardService {

    @Autowired
    private CountCardRepository countCardRepository;

    @Override
    protected JpaRepository<CountCard, Long> getRepository() {
        return countCardRepository;
    }

    @Override
    public List<CountCard> findByStatus(Integer status) {
        return countCardRepository.findByStatus(status);
    }

    @Override
    public List<CountCard> findActivePromotions() {
        LocalDateTime now = LocalDateTime.now();
        return countCardRepository.findByStartTimeLessThanEqualAndEndTimeGreaterThanEqual(now, now);
    }

    @Override
    public boolean purchaseCountCard(Long cardId, Long userId) {
        // 实际实现中需要记录用户购买次数权益卡的信息
        // 这里仅做简单示例
        CountCard card = findById(cardId);
        if (card != null && card.getStatus() == 1) { // 1表示进行中
            // 检查库存
            if (card.getSoldQuantity() >= card.getTotalQuantity()) {
                return false;
            }
            // 增加已售出数量
            card.setSoldQuantity(card.getSoldQuantity() + 1);
            update(card);
            return true;
        }
        return false;
    }

    @Override
    public boolean useCountCard(Long cardId, Long userId) {
        // 实际实现中需要记录用户使用次数权益卡的信息
        // 这里仅做简单示例
        CountCard card = findById(cardId);
        if (card != null && card.getStatus() == 1) { // 1表示进行中
            // 检查剩余次数
            if (getRemainingCount(cardId, userId) <= 0) {
                return false;
            }
            // 检查使用时间是否在有效期内
            LocalDateTime now = LocalDateTime.now();
            if (now.isBefore(card.getStartTime()) || now.isAfter(card.getEndTime())) {
                return false;
            }
            // 实际实现中需要减少用户的剩余次数
            return true;
        }
        return false;
    }

    @Override
    public int getRemainingCount(Long cardId, Long userId) {
        // 实际实现中需要查询用户的剩余次数
        // 这里仅做简单返回，实际应用中需要连接到用户持有卡记录表
        CountCard card = findById(cardId);
        return card != null ? card.getTotalCount() : 0;
    }

}